# Created by 黄景涛
# DATE: 2024/12/10

import logging
import logging.config
import os
from config.settings import ROOT_PATH, LOGGING_CONFIG
from config.settings import LogColors

# 检查日志目录是否存在
log_dir = os.path.join(ROOT_PATH, 'logs')
os.makedirs(log_dir, exist_ok=True)


class ColoredFormatter(logging.Formatter):
    """ 定制日志格式化器，继承logging.Formatter """

    # 日志等级与颜色的映射表
    LOG_COLORS = {
        logging.DEBUG: LogColors.BLUE,
        logging.INFO: LogColors.GREEN,
        logging.WARNING: LogColors.YELLOW,
        logging.ERROR: LogColors.RED,
        logging.CRITICAL: LogColors.MAGENTA,
    }

    def format(self, record):
        """ format方法重写：对父类返回的message做二次加工 """
        root_parent_path = os.path.dirname(ROOT_PATH)
        record.pathname = os.path.relpath(record.pathname, root_parent_path)
        message = super().format(record)

        color = self.LOG_COLORS.get(record.levelno, LogColors.RESET)
        return f"{color}{message}{LogColors.RESET}"


def get_logger(name=None):
    """
    获取日志记录器实例
    :param name: 记录器名称
    :return: 记录器
    """
    if not logging.getLogger().hasHandlers():
        logging.config.dictConfig(LOGGING_CONFIG)

    logger_inst = logging.getLogger(name)

    # 设置自定义的格式化器
    formatter = ColoredFormatter(fmt=LOGGING_CONFIG['formatters']['standard']['format'],
                                 datefmt=LOGGING_CONFIG['formatters']['standard']['datefmt'])

    for handler in logger_inst.handlers:
        if isinstance(handler, logging.FileHandler):
            pass
        elif isinstance(handler, logging.StreamHandler):
            handler.setFormatter(formatter)

    return logger_inst


# logger记录器实例
logger = get_logger()

if __name__ == '__main__':
    logger.debug("这是调试信息")
    logger.info("这是信息")
    logger.warning("这是警告")
    logger.error("这是错误")
    logger.critical("这是严重错误")
